package com.yunshu.yunshuapp.kuaixun;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunshu.yunshuapp.ImageActivity;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.kuaixun.KuaixundetailActivity;
import com.yunshu.yunshuapp.OnTapListener;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.banner.BannerClass;
import com.yunshu.yunshuapp.banner.ScrollBanner;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.user.LoginActivity;
import com.yunshu.yunshuapp.user.UserInfoActivity;
import com.yunshu.yunshuapp.user.YSUser;
import com.yunshu.yunshuapp.utils.YSUtils;
import com.yunshu.yunshuapp.views.SegmentControlView;
import com.yunshu.yunshuapp.xianhuo.AddBaojiaActivity;
import com.yunshu.yunshuapp.zixunlist.ZixunListModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;

public class KuaixunListActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener, View.OnClickListener, TimePicker.OnTimeChangedListener {

    private static final int MSG_RECYLEVIEW_UPDATE = 100;

    private int pageIndex = 0;
    private RecyclerView mRecyclerView;
    private String[] ads;
    private ArrayList<KuaixunListModel> models;
    private com.yunshu.yunshuapp.kuaixun.KuaixunListAdapter adapter;
    private YSRequest bannerRequest;
    private YSRequest request;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Handler mExtHandler;

    private TextView startTimeTV;
    private TextView endTimeTV;
    private TextView categoryTV;
    private RelativeLayout searchView;
    private Boolean isStartTime;
    private String tempDate="";
    private String tempTime="";
    private String filterStartTime="";
    private String filterEndTime="";
    private String filterCategory = "";

    private int listType = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kuaixun_list);

        KuaixunListModel.readListFromPersistence(this);

        bannerRequest = new YSRequest(this);
        request = new YSRequest(this);

        Bundle bundle = this.getIntent().getExtras();

        if(bundle == null || bundle.get("listtype") == null){
            this.addList();
        }

        NavigationBar bar = (NavigationBar) findViewById(R.id.navigationBar);
        bar.putInActivity(this);
        bar.setTitle("快讯");
        bar.setOnMenuItemClickListener(this);
        this.addSegement();
        this.requestBanner();

        this.initLoadMoreListener();
        mExtHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_RECYLEVIEW_UPDATE:
                        adapter.setModels(models);
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };

        KuaixunListModel.readListFromPersistence(this);

        startTimeTV = (TextView) findViewById(R.id.startTime);
        endTimeTV = (TextView) findViewById(R.id.endTime);
        categoryTV = (TextView) findViewById(R.id.category);
        searchView = (RelativeLayout) findViewById(R.id.searchView);
        View startLayout = findViewById(R.id.startTimeLayout);
        startLayout.setOnClickListener(this);
        View endLayout = findViewById(R.id.endTimeLayout);
        endLayout.setOnClickListener(this);
        View categoryLayout = findViewById(R.id.categoryLayout);
        categoryLayout.setOnClickListener(this);
        Button cancel = (Button) findViewById(R.id.cancel);
        cancel.setOnClickListener(this);
        Button ok = (Button) findViewById(R.id.ok);
        ok.setOnClickListener(this);

        View markLayout = findViewById(R.id.searchView);
        markLayout.setOnClickListener(this);

        Calendar mycalendar=Calendar.getInstance();
        int year = mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年
        int month = mycalendar.get(Calendar.MONTH);//获取Calendar对象中的月
        int day = mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
        tempDate = year + "-" + month + "-" + day;

        int hour = mycalendar.get(Calendar.HOUR);
        int minute = mycalendar.get(Calendar.MINUTE);
        tempTime = String.valueOf(hour) + ":" + String.valueOf(minute);

    }

    private void addSegement() {
        SegmentControlView segement = (SegmentControlView) findViewById(R.id.scv);

        segement.setOnSegmentChangedListener(new SegmentControlView.OnSegmentChangedListener() {
            @Override
            public void onSegmentChanged(int newSelectedIndex) {
                if (newSelectedIndex != listType ) {
                    listType = newSelectedIndex;
                    refresh();
                }
            }
        });
        //set viewpager to change segment according to the state of viewpager
        //set the selected index of segments initiatively
        segement.setSelectedIndex(0);
        //set gradient effect if you want
        segement.setGradient(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        KuaixunListModel.persistentReadList(this);
    }

    private void refresh() {
        if (!request.getIsCompleted())return;
        pageIndex = 1;
        String params = "";
        if (listType == 1 && this.filterCategory.length() == 0 ){
            params = "&page=1" ;
        }else {
            String idList = this.filterCategory.length() == 0 ? YSUser.instance().getKuaixunChannels() : this.filterCategory ;
            params = "&page=1&names=" + idList ;
        }
        if (filterStartTime.length() > 0){
            params += "&starttime=" + filterStartTime;
        }
        if (filterEndTime.length() > 0){
            params += "&endtime=" + filterEndTime;
        }

        request.GET(YSRequest.Kuaixun_LIST, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<KuaixunListModel> temp = new ArrayList<KuaixunListModel>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        KuaixunListModel model = mapper.readValue(jsonstr, KuaixunListModel.class);
                        model.updateIsRead();
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                models = temp;
                pageIndex +=1;
                reloadData();
            }
        });
    }

    private void loadmore() {
        if (!request.getIsCompleted())return;

        String params = "";
        if (listType == 1 && this.filterCategory.length() == 0 ){
            params = "&page=" + pageIndex;
        }else {
            String idList = this.filterCategory.length() == 0 ? YSUser.instance().getKuaixunChannels() : this.filterCategory ;
            params = "&page="+ pageIndex + "&names=" + idList ;
        }
        if (filterStartTime.length() > 0){
            params += "&starttime=" + filterStartTime;
        }
        if (filterEndTime.length() > 0){
            params += "&endtime=" + filterEndTime;
        }

        request.GET(YSRequest.Kuaixun_LIST,params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<KuaixunListModel> temp = new ArrayList<KuaixunListModel>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        KuaixunListModel model = mapper.readValue(jsonstr, KuaixunListModel.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                pageIndex +=1;
                models.addAll( temp);
                reloadData();
            }
        });
    }

    private void endRefreshing() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
            }
        });


    }

    private void requestBanner(){
        bannerRequest.GET(YSRequest.ZIXUN_Banner, null, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                refresh();
                if (isSuccess != YSRequest.REQUEST_OK || !result.isArray()){
                    showBanner(null);
                    return;
                }
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<BannerClass> temp = new ArrayList<BannerClass>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        BannerClass model = mapper.readValue(jsonstr, BannerClass.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                showBanner(temp);
            }

        });
    }

    private void showBanner(final ArrayList<BannerClass> temp) {

        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                if(temp == null || temp.size() == 0){
                    return;
                }
                ScrollBanner bannerView = getBanner();
                ArrayList<String> imgUrls = new ArrayList<String>();
                for (BannerClass banner : temp){
                    imgUrls.add(banner.getImgUrl());
                }
                ads =  imgUrls.toArray(new String[]{});
                bannerView.setImages(ads);
                adapter.setBanner(bannerView);
            }
        });

    }

    private void reloadData() {
//        runOnUiThread(new Runnable() {      // UI thread
//            @Override
//            public void run() {
//                adapter.models = models;
//                adapter.notifyDataSetChanged();
//            }
//        });
        Message msg;
        msg = Message.obtain();
        msg.what = MSG_RECYLEVIEW_UPDATE;
        mExtHandler.sendMessage(msg);

    }

    private void addList() {
        mRecyclerView = (RecyclerView) findViewById(R.id.list_view);
        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        //设置RecycleView的显示方向：（默认为垂直） 水平
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);

        adapter = new com.yunshu.yunshuapp.kuaixun.KuaixunListAdapter(getBaseContext());
        adapter.activity = KuaixunListActivity.this;
        mRecyclerView.setAdapter(adapter);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        //设置刷新时动画的颜色，可以设置4个
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }


    private ScrollBanner getBanner() {
        int screenWidth = YSUtils.screenWidth(this); // 获取屏幕宽度
        final ScrollBanner banner = new ScrollBanner(this);
        ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(screenWidth, (int) (screenWidth*0.43));
//        layout.width = screenWidth;
//        layout.height = (int) (screenWidth*0.43);
        banner.setLayoutParams(layout);

        banner.bannerClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int index = banner.indexOfView(v);
                Intent intent = new Intent();
                intent.setClass(KuaixunListActivity.this, ImageActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("imgUrl",ads[index]);
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
//                MainActivity.this.finish();
            }
        };
        return banner;
    }

    private void initLoadMoreListener() {

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem ;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==adapter.getItemCount()){

                    loadmore();


                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem=layoutManager.findLastVisibleItemPosition();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_kuaixun , menu);
        menu.getItem(0).setTitle("搜索");
        return true;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_subscribeKuaixun:

                this.searchView.setVisibility(View.VISIBLE);
                break;
            default:break;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.startTimeLayout){
            isStartTime = true;
            this.chooseTime();
        }else if (view.getId() == R.id.endTimeLayout){
            isStartTime = false;
            this.chooseTime();
        }else if(view.getId() == R.id.categoryLayout){
//            this.
            Intent intent = new Intent();
            intent.setClass(this, KuaixunSubscribeActivity.class);
            intent.putExtra("selection",true);
            intent.putExtra("title","请选择类别");
            startActivityForResult(intent, KuaixunSubscribeActivity.REQUEST_CODE);
        }else if(view.getId() == R.id.cancel){
            this.searchView.setVisibility(View.INVISIBLE);
        }else if(view.getId() == R.id.ok){
            this.searchView.setVisibility(View.INVISIBLE);
            this.refresh();
        }else if(view.getId() == R.id.searchView) {
            this.searchView.setVisibility(View.INVISIBLE);
        }
    }


    private void chooseTime(){

        //初始化Calendar日历对象
        Calendar mycalendar=Calendar.getInstance();
        int year = mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年
        int month = mycalendar.get(Calendar.MONTH);//获取Calendar对象中的月
        int day = mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天

        //创建DatePickerDialog对象
        DatePickerDialog dpd=new DatePickerDialog(this,Datelistener,year,month,day);
        dpd.show();//显示DatePickerDialog组件
    }

    private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener()
    {

        /**params：view：该事件关联的组件
         * params：myyear：当前选择的年
         * params：monthOfYear：当前选择的月
         * params：dayOfMonth：当前选择的日
         */
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {


            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            int year = myyear;
            int month = monthOfYear + 1;
            int day = dayOfMonth;
            //更新日期
            updateDate(year, month,day);



            AlertDialog.Builder builder2 = new AlertDialog.Builder( KuaixunListActivity.this );
            builder2.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
//                    if (time.length() > 0) { //清除上次记录的日期
//                        time.delete(0, time.length());
//                    }

//                    timeLabel.setText( tempTime );
                    dialog.dismiss();
                }
            });
            builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            Calendar calendar = Calendar.getInstance();

            int hour = calendar.get(Calendar.HOUR);
            int minute = calendar.get(Calendar.MINUTE);

            AlertDialog dialog2 = builder2.create();
            View dialogView2 = View.inflate(KuaixunListActivity.this, R.layout.dialog_time, null);
            TimePicker timePicker = (TimePicker) dialogView2.findViewById(R.id.timePicker);
            timePicker.setCurrentHour(hour);
            timePicker.setCurrentMinute(minute);
            timePicker.setIs24HourView(true); //设置24小时制
            timePicker.setOnTimeChangedListener(KuaixunListActivity.this);
            dialog2.setTitle("设置时间");
            dialog2.setView(dialogView2);
            dialog2.show();

        }

    };

    @Override
    public void onTimeChanged(TimePicker timePicker, int hour, int minute) {

        tempTime = String.valueOf(hour) + ":" + String.valueOf(minute);
        String timeString = tempDate + " " + tempTime;
        if (isStartTime){
            startTimeTV.setText("开始时间："+timeString);
            filterStartTime = timeString;
        }else{
            endTimeTV.setText("结束时间："+timeString);
            filterEndTime = timeString;
        }
    }

    private void updateDate(int year, int month, int day) {

        tempDate = year + "-" + month + "-" + day;

        String timeString = tempDate + " " + tempTime;
        if (isStartTime){
            startTimeTV.setText("开始时间："+timeString);
            filterStartTime = timeString;
        }else{
            endTimeTV.setText("结束时间："+timeString);
            filterEndTime = timeString;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK
                && requestCode == KuaixunSubscribeActivity.REQUEST_CODE){
            categoryTV.setText("类别:" + data.getStringExtra("data")) ;
            this.filterCategory = data.getStringExtra("data");
        }
    }
}
